﻿using System.Runtime.InteropServices;

namespace DHTools
{
    public class Zlib
    {
        [DllImport("zlib.dll")]
        public static extern int uncompress(byte[] dest, ref ulong destLen, byte[] source, ulong souLen);

        public static byte[] UncompressData(byte[] source)
        {
            ulong sourceLen = (ulong)source.Length;
            ulong destLen = sourceLen * 2; // 初始缓冲区大小
            byte[] dest = new byte[destLen];
            int result = -5; // Z_BUF_ERROR

            while (result == -5)
            {
                result = uncompress(dest, ref destLen, source, sourceLen);
                if (result == -5)
                {
                    destLen *= 2; // 扩大缓冲区
                    dest = new byte[destLen];
                }
            }

            if (result == 0) // Z_OK
            {
                Array.Resize(ref dest, (int)destLen); // 调整数组大小为实际解压后大小
                return dest;
            }
            else
            {
                throw new Exception("解压缩失败，错误代码: " + result);
            }
        }
    }
}